package com.xliang.spider.version01;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 解析极客学院网页，下载教学视频
 * 
 * @author xiongl
 *
 */
public class SpiderV01
{
    private static final String path = "E:\\web\\";
    
    @SuppressWarnings("unused")
    private static int item = 1;
    
    public static void parseRoot(String url)
        throws IOException
    {
        Document document = Jsoup.connect(url).get();
        Elements rootDoc = document.getElementsByTag("table");
        Iterator<Element> it = rootDoc.iterator();
        while (it.hasNext())
        {
            Elements elements = it.next().getElementsByTag("a");
            for (Element element : elements)
            {
                String href = element.getElementsByTag("a").attr("href");
                String title = element.getElementsByTag("a").attr("title");
                System.out.println("正在扫描" + title + "下的视频列表");
                parseChild(href);
            }
        }
    }
    
    public static void parseChild(String url)
        throws IOException
    {
        Document document = Jsoup.connect(url).get();
        System.out.println(document.html());
        Elements vidoDiv = document.getElementsByClass("video-list").first().select("h2 > a");
        for (Element ele : vidoDiv)
        {
            String href = ele.attr("href");
            String name = ele.text().replaceAll(" ", "");
            System.out.println(name + "    " + href);
            // downLoadVido(href, name, item);
        }
    }
    
    public static void downLoadVido(String url, String fileName, int index)
        throws IOException
    {
        InputStream inputStream = null;
        OutputStream outStream = null;
        try
        {
            System.out.println("开始下载视频：" + fileName);
            Document document = Jsoup.connect(url).cookies(createCookies()).get();
            Element video = document.getElementsByTag("source").first();
            if (video != null)
            {
                String name = path + String.format("%03d.%s", index, fileName) + ".mp4";
                String videoUrl = video.attr("src");
                HttpClient client = HttpClientBuilder.create().build();
                HttpGet request = new HttpGet(url);
                HttpResponse response = client.execute(request);
                if (response == null)
                {
                    System.err.println(String.format("下载%03d.%s出错，请求失败", index, fileName));
                }
                else
                {
                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
                    {
                        File file = new File(name);
                        outStream = new FileOutputStream(file);
                        item++;
                        System.out.println("视频：" + fileName + "下载成功");
                    }
                    else
                    {
                        System.err.println(String.format("下载%03d.%s出错，errorCode = %d", index, fileName, response.getStatusLine().getStatusCode()));
                        System.exit(0);
                    }
                }
            }
            else
            {
                System.err.println(String.format("下载%03d.%s出错", index, fileName));
                System.exit(0);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (outStream != null)
            {
                outStream.close();
            }
            if (inputStream != null)
            {
                inputStream.close();
            }
        }
        
    }
    
    public static void downLoadVido(String url)
    {
    
    }
    
    public static void getCapture()
    {
        try
        {
            while (true)
            {
                HttpClient client = HttpClientBuilder.create().build();
                HttpGet request = new HttpGet("http://passport.jikexueyuan.com/sso/verify?" + new Date().getTime());
                HttpResponse response = client.execute(request);
                if (response == null)
                {
                    System.out.println("验证码获取失败，重新获取");
                    continue;
                }
                else
                {
                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
                    {
                        String picName = "capture.jpg";
                        File image = new File(picName);
                        OutputStream outStream = new FileOutputStream(image);
                        response.getEntity().writeTo(outStream);
                        outStream.close();
                        System.out.println("验证码获取成功");
                        break;
                    }else
                    {
                        System.out.println("验证码获取失败，重新获取，errorCode="+response.getStatusLine().getStatusCode());
                        continue;
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
    }
    
    public static Map<String, String> createCookies()
    {
        Map<String, String> cookies = new HashMap<String, String>();
        cookies.put("HMACCOUNT", "7FA062A719A27CC0");
        cookies.put("Hm_lpvt_f3c68d41bda15331608595c98e9c3915", "1449738920");
        cookies.put("Hm_lvt_f3c68d41bda15331608595c98e9c3915", "1449738007,1449738081,1449738862,1449738920");
        cookies.put("MECHAT_CKID", "cookieVal=006600144973896516586512");
        cookies.put("MECHAT_LVTime", "1449738920475");
        cookies.put("PHPSESSID", "s90tbpv8qo617fec9a4tjmacs7");
        cookies.put("QINGCLOUDELB", "7e36c8b37b8339126ed93010ae808701d562b81daa2a899c46d3a1e304c7eb2b|VmlC2|VmlC2");
        cookies.put("QINGCLOUDELB", "3505c02c34c678355ea7a99381335e4dd562b81daa2a899c46d3a1e304c7eb2b|VmlC2|Vmk/R");
        cookies.put("_ga", "GA1.2.980711190.1449738920");
        cookies.put("_gat", "1");// 固定
        cookies.put("authcode", "f346ucQWBZatAQSeOtNHWc+7hfzYWuPgGZYDdQKrtDsbBxa6zcM4sXMHtudx5BgjyK10WMQewUOGZVawmOqHUgVZ4Mzr3e6x9ctNRdS4pBBtAPCGDuxW1BZu8Magc5rq");
        cookies.put("code", "CNLWMU");// 固定
        cookies.put("connect.sid", "s:HQS0dXqMZ_sEnUbq2vulgavZqm6Mlq7I.R+mT+/qK9JlegN96+jcGJwjQpI9E2E73/8szGger2JQ");
        cookies.put("domain", "5237107750");// 固定
        cookies.put("is_expire", "0");// 固定
        cookies.put("level_id", "3");// 固定
        cookies.put("mobileid", "006600144973896516586512");// 固定
        cookies.put("stat_isNew", "1");// 固定
        cookies.put("stat_ssid", "1450141320352");
        cookies.put("stat_uuid", "1449738919840921817411");
        cookies.put("uid", "3833929");// 固定
        cookies.put("uname", "jike_8835661");// 固定
        return cookies;
    }
    
    public static void main(String[] args)
        throws IOException
    {
        // parseRoot("http://ke.jikexueyuan.com/zhiye/web/");
        // parseChild("http://www.jikexueyuan.com/course/827.html");
        // downLoadVido("http://www.jikexueyuan.com/course/245.html");
        //parseChild("http://www.jikexueyuan.com/course/245.html");
        getCapture();
    }
}
